package ru.arriah.servicedesk.web.leadExecutor.action;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Locale;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.GroupBean;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.RequestPriorityBean;
import ru.arriah.servicedesk.bean.RequestTypeBean;
import ru.arriah.servicedesk.bean.TaskBean;
import ru.arriah.servicedesk.bean.error.RequestFormErrorBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;
import ru.arriah.servicedesk.web.commonaction.exception.PrivilegesException;

public class ProcessEditFormAction extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;
   protected EmployeeManagerLocalHome employeeManagerLocalHome;
   protected GroupManagerLocalHome groupManagerHome;   
   protected RequestFormErrorBean requestFormErrorBean;

   public ProcessEditFormAction() throws NamingException {
      super();
      
      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
      
      groupManagerHome =
        Utils.getGroupManagerHomeInterface();
      
      employeeManagerLocalHome =
        Utils.getEmployeeManagerHomeInterface();
   }
   
   
   /**
    * Restore requestBean from httpRequest
    * @param request
    * @return
    */
   RequestBean restoreBean(HttpServletRequest request) {            
      RequestBean requestBean = new RequestBean();
      DateFormat dateformat = 
          DateFormat.getDateInstance(
             DateFormat.SHORT, 
             new Locale("ru")
          );
      
      int requestId = idVal(request.getParameter("request_id"));
      int userId = Utils.getUserId(request);
      
      requestBean.setId(requestId);
      requestBean.setClientText(request.getParameter("text"));
      requestBean.setDispatcherText(request.getParameter("dispatcherText"));                     
      requestBean.setGroupId(idVal(request.getParameter("group_id")));
      requestBean.setRequestTypeId(idVal(request.getParameter("requesttype_id")));                            
      requestBean.setPriority(idVal(request.getParameter("priority")));
      requestBean.setComment(request.getParameter("comment"));
      requestBean.setLeadExecutorId(userId);
      requestBean.setName(request.getParameter("name"));
      
      try {
        requestBean.setApproxEndDate(
          dateformat.parse(request.getParameter("approxEndDate"))
        );
      } catch (Exception e) {/*nop*/}
      
      return requestBean;
   }
   
   
   
   /**
    * Form validation
    * @param requestBean
    * @param requestManager
    * @return
    */
   private boolean isValid(
     RequestBean requestBean, 
     RequestBean rb
   ) {
     boolean valid = true;
     
     requestFormErrorBean = new RequestFormErrorBean();          
     
     
     if ((requestBean.getDispatcherText() == null) || requestBean.getDispatcherText().equals("")) {
       requestFormErrorBean.setDispatcherText(
         config.getProperty("ERROR.REQUESTFORM.DISPATCHERTEXT")
       );
       valid = false;
     }
     
     if (requestBean.isEmpty(requestBean.getName())) {
        requestFormErrorBean.setName(
          config.getProperty("ERROR.REQUESTFORM.NAME")
        );
        valid = false;
      }
     
     if (requestBean.getRequestTypeId() == 0) {
       requestFormErrorBean.setRequestType(
         config.getProperty("ERROR.REQUESTFORM.REQUESTTYPE")
       );
       valid = false;
     }
     
     if (requestBean.getApproxEndDate() == null) {
       requestFormErrorBean.setApproxEndDate(
         config.getProperty("ERROR.REQUESTFORM.APPROX_END_DATE")
       );
       valid = false;
     } else {       
       if (
         (rb.getRegistrationDate().after(requestBean.getApproxEndDate())) &&
         !sameDay(rb.getRegistrationDate(), requestBean.getApproxEndDate())
       ) {
         requestFormErrorBean.setApproxEndDate(
           String.format(
             config.getProperty("ERROR.REQUESTFORM.REGDATE_AFTER_END"),
             rb.getRegistrationDate()
           )
         );
         valid = false;
       }
     }    
     
     if (requestBean.getPriority() == 0) {
       requestFormErrorBean.setPriority(
         config.getProperty("ERROR.REQUESTFORM.PRIORITY")
       );
       valid = false;
     }
     
     return valid;
   }

   
   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {
        RequestManagerLocalObject requestManager = 
           requestManagerHome.create();                            
       
        int userId = Utils.getUserId(request);                              
       
        RequestBean requestBean = this.restoreBean(request);
        
        RequestBean rb = 
           requestManager.selectRequest(requestBean.getId());
        
        if (rb.getLeadExecutorId() != userId)
           throw new PrivilegesException();                                                 
       
        
        if (!isValid(requestBean, rb)) {
            GroupManagerLocalObject groupManager = 
               groupManagerHome.create();

            Collection<GroupBean> groupsList = 
               groupManager.selectGroups();

            Collection<RequestTypeBean> requestTypesList = 
               requestManager.selectRequestTypes();

            Collection<RequestPriorityBean> priorityList = 
               requestManager.selectPriorityList();

            groupManager.remove();

            addErrorMessage(
               request,
               config.getProperty("ERROR.REQUESTFORM_FIELDS_INVALID")
            );

            request.setAttribute("priorityList", priorityList);
            request.setAttribute("requestTypesList", requestTypesList);
            request.setAttribute("groupsList", groupsList);
            request.setAttribute("requestBean", requestBean);
            request.setAttribute("error", requestFormErrorBean);
            request.setAttribute("action", request.getParameter("action"));
            return actionMapping.getFailureTarget();
        }    
       
       Action action = Action.valueOf(actionMapping.getActionName());
       
       switch (action) {
          case commitRequest:
             requestBean.setStatusId(4); //active status
             boolean result = requestManager.updateRequestByLeadExecutor(requestBean, userId);
             
             if(result) {
                Collection<TaskBean> tasksList = 
                   requestManager.selectTasksByRequest(requestBean.getId());
                
                addInfMessage(
                  request,
                  config.getProperty("INF.REQUEST_COMMITTED")
                );
             }
             break;
             
          case updateRequest:
             requestBean.setStatusId(rb.getStatusId()); //old status
             if (requestManager.updateRequestByLeadExecutor(requestBean, userId))
                addInfMessage(
                  request,
                  config.getProperty("INF.REQUEST_UPDATED")
                );
             break;
             
          default:
             throw new RuntimeException("Unsupported action " + action);
       }                                                                         
         
       requestManager.remove();
       
              
       //execute RequestDetailsAction          
       
       RequestDetailsAction requestDetailsAction = 
         new RequestDetailsAction(requestManagerHome, config);
                                           
       return requestDetailsAction.execute(actionMapping, request, response);
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}